package fragmentson;

import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import java.util.ArrayList;
import java.util.List;

import activity.SonActivity;
import bean.MessageForSimple;
import fragmentson.backhandle.BackHandledFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;
import util.adapter.SearchAdapter;

/**
 * 添加围栏
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class Rall_B extends BackHandledFragment implements AMap.OnMyLocationChangeListener,Inputtips.InputtipsListener {

	private View rootView;
	private TextureMapView mapView;
	private AMap aMap;
	//mode 0基础地图1卫星地图 road 0路况模式 1非路况模式
	private int mode=0,road=0,radius=100;
	private View ll_sosarea;
	private GeocodeSearch geocoderSearch;
	private TextView tv_address,tv_radius;
	private SeekBar timeline;
	private ImageView iv_in,iv_out;
	private String isin ="true",isout = "true";
	private View ll_search;
	private ListView lv_searchlist;
	private SearchAdapter adapter;
	private EditText et_search;
	private String regionid="",centerLat="",centerLng="",name="";
	List<Tip> mlist = new ArrayList<>();
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_rall_b, null);
		/*初始化地图和amap对象*/
		mapView = (TextureMapView) rootView.findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		if (aMap == null) {
			aMap = mapView.getMap();
		}
		regionid = getArguments().getString("regionid");
		if(!regionid.equals("")){
			centerLat = getArguments().getString("centerLat");
			centerLng = getArguments().getString("centerLng");
			name = getArguments().getString("name");
			isin = getArguments().getString("isin");
			isout = getArguments().getString("isout");
			radius = Integer.valueOf(getArguments().getString("radius"));
		}

		initView();
		initMapView();
		return rootView;
	}

	private void initView() {
		// TODO Auto-generated method stub
		rootView.findViewById(R.id.tv_login).setOnClickListener(listener);
		ll_sosarea = rootView.findViewById(R.id.ll_sosarea);
		tv_radius = ((TextView) rootView.findViewById(R.id.tv_radius));
		tv_address = ((TextView) rootView.findViewById(R.id.tv_address));
		iv_in = ((ImageView) rootView.findViewById(R.id.iv_in));
		iv_out = ((ImageView) rootView.findViewById(R.id.iv_out));
		ll_search = rootView.findViewById(R.id.ll_search);
		rootView.findViewById(R.id.tv_cancel).setOnClickListener(listener);
		rootView.findViewById(R.id.tv_search).setOnClickListener(listener);
		iv_in.setOnClickListener(listener);
		iv_out.setOnClickListener(listener);
		rootView.findViewById(R.id.iv_subtract).setOnClickListener(listener);
		rootView.findViewById(R.id.iv_plus).setOnClickListener(listener);
		tv_radius.setText(radius+getResources().getString(R.string.mi));
		timeline = ((SeekBar) rootView.findViewById(R.id.timeline));
		timeline.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				Log.d("seekbar",progress+"");
				radius = 100+progress;
				tv_radius.setText(radius+getResources().getString(R.string.mi));
				draw();
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}
		});

		lv_searchlist = ((ListView) rootView.findViewById(R.id.lv_searchlist));
		et_search = ((EditText) rootView.findViewById(R.id.et_search));
		et_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence cs, int start, int before, int count) {
				// TODO Auto-generated method stub
				InputtipsQuery inputquery = new InputtipsQuery(et_search.getText().toString().trim(), "");
				inputquery.setCityLimit(false);//不限制在当前城市
				Inputtips inputTips = new Inputtips(getActivity(), inputquery);
				inputTips.setInputtipsListener(Rall_B.this);
				inputTips.requestInputtipsAsyn();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
		});

		adapter = new SearchAdapter(getActivity(),mlist);
		lv_searchlist.setAdapter(adapter);
		lv_searchlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				getAddress(mlist.get(position).getPoint().getLatitude(), mlist.get(position).getPoint().getLongitude());
				ll_search.setVisibility(View.GONE);
				AlphaAnimation animation1 = new AlphaAnimation(1.0f, 0.1f);
				animation1.setDuration(250);
				ll_search.setAnimation(animation1);

				InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et_search.getWindowToken(), 0);
			}
		});


	}

	private void initMapView(){
		//隐藏缩放组件
		aMap.getUiSettings().setZoomControlsEnabled(false);
		//logo位置
		aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
		//加载定位maker
		//initMarkers()
		// 初始化反地理编码;
		initGeocoder();

		aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
			@Override
			public void onTouch(MotionEvent motionEvent) {
				draw();
			}
		});
		//中点监听
		aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
			@Override
			public void onCameraChange(CameraPosition cameraPosition) {
				centerLng = cameraPosition.target.longitude+"";
				centerLat = cameraPosition.target.latitude+"";
			}

			@Override
			public void onCameraChangeFinish(CameraPosition cameraPosition) {
				//中点变化监听 用在做反地理编码
				LatLng latLng =cameraPosition.target;//获得中点经纬度
				LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
				RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
				geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
				draw();
			}
		});
		aMap.setOnMyLocationChangeListener(this);
		if(regionid.equals("")) {
			//添加时才启动定位
			locationBlue();
		}else{
			//编辑时加载状态
			iv_in.setImageResource(isin.equals("true")?R.mipmap.rall_checked:R.mipmap.rall_unchecked);
			iv_out.setImageResource(isout.equals("true")?R.mipmap.rall_checked:R.mipmap.rall_unchecked);
			tv_radius.setText(radius+getResources().getString(R.string.mi));
			timeline.setProgress(radius-100);
			((EditText) rootView.findViewById(R.id.et_rallname)).setText(name);
			getAddress(Double.valueOf(centerLat),Double.valueOf(centerLng));
		}

	}

	public void locationBlue(){
		MyLocationStyle myLocationStyle;
		myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
		myLocationStyle.strokeColor(Color.argb(0,0,0,0));
		myLocationStyle.radiusFillColor(Color.argb(0,0,0,0));//设置定位蓝点精度圆圈的填充颜色的方法。
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.icon_transparency));// 设置小蓝点的图标
		myLocationStyle.anchor(0.5f,0.8f);
		//myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//指定为一次并拉到中心
		myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//指定为一次并拉到中心
		myLocationStyle.interval(10000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
		aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
		aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
	}

	/**
	 * 绘制电子围栏圈
	 */
	public void draw() {
		float scale = aMap.getScalePerPixel();
		float diameter = radius*2/scale;
		LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) ll_sosarea
				.getLayoutParams();
		linearParams.height = (int)(diameter);
		linearParams.width = (int)(diameter);
		ll_sosarea.setLayoutParams(linearParams);
	}

	public static Rall_B newInstance(String regionid, String centerLat, String centerLng, String name, String isin, String isout, String radius) {
		Rall_B fragment = new Rall_B();
		Bundle bundle = new Bundle();
		bundle.putString("regionid",regionid);
		bundle.putString("centerLat",centerLat);
		bundle.putString("centerLng",centerLng);
		bundle.putString("name",name);
		bundle.putString("isin",isin);
		bundle.putString("isout",isout);
		bundle.putString("radius",radius);
		fragment.setArguments(bundle);
		return fragment;
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
				case R.id.iv_subtract:
					if(radius>100){
						radius = radius-100;
					}
					timeline.setProgress(radius-100);
					break;
				case R.id.iv_plus:
					if(radius<1000){
						radius = radius+100;
						if(radius>1000){
							radius = 1000;
						}
					}
					timeline.setProgress(radius-100);
					break;
				case R.id.iv_in:
					if(isin.equals("true")){
						iv_in.setImageResource(R.mipmap.rall_unchecked);
						isin = "false";
					}else{
						iv_in.setImageResource(R.mipmap.rall_checked);
						isin = "true";
					}
					break;
				case R.id.iv_out:
					if(isout.equals("true")) {
						iv_out.setImageResource(R.mipmap.rall_unchecked);
						isout = "false";
					}else{
						iv_out.setImageResource(R.mipmap.rall_checked);
						isout = "true";
					}
					break;
				case R.id.tv_cancel:
					ll_search.setVisibility(View.GONE);
					AlphaAnimation animation1 = new AlphaAnimation(1.0f, 0.1f);
					animation1.setDuration(250);
					ll_search.setAnimation(animation1);

					InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(et_search.getWindowToken(), 0);

					break;
				case R.id.tv_search:
					ll_search.setVisibility(View.VISIBLE);
					AlphaAnimation animation = new AlphaAnimation(0.1f, 1.0f);
					animation.setDuration(250);
					ll_search.setAnimation(animation);

					et_search.setFocusable(true);
					et_search.setFocusableInTouchMode(true);
					et_search.requestFocus();
					InputMethodManager inputManager = (InputMethodManager)et_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
					inputManager.showSoftInput(et_search, 0);
					break;
				case R.id.tv_login:
					ApiUtil.getApiService().saveSafeRegion(DemoApplication.getToken(),DemoApplication.getDeviceid(),regionid,centerLng,centerLat,radius+"",((EditText) rootView.findViewById(R.id.et_rallname)).getText().toString(),tv_address.getText().toString(),isin,isout).enqueue(new Callback<MessageForSimple>() {
						@Override
						public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
							try {
								MessageForSimple entity = response.body();
								if(entity.getCode().equals("10008")){
									((SonActivity) getActivity()).backTask();
								}else{
									Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						@Override
						public void onFailure(Call<MessageForSimple> call, Throwable t) {
							Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
						}
					});
					break;
				default:
					break;
			}
		}
	};

	@Override
	public boolean onBackPressed() {
		return false;
	}

	/**
	 * 初始化逆地理编码组件
	 */
	private void initGeocoder(){
		geocoderSearch = new GeocodeSearch(getActivity());
		geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
			@Override
			public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

				if (rCode == AMapException.CODE_AMAP_SUCCESS) {
					if (result != null && result.getRegeocodeAddress() != null
							&& result.getRegeocodeAddress().getFormatAddress() != null) {
						//Toast.makeText(getActivity(),result.getRegeocodeAddress().getFormatAddress(),Toast.LENGTH_LONG).show();
						tv_address.setText(result.getRegeocodeAddress().getFormatAddress());

					} else {
						Toast.makeText(getActivity(),"无数据",Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(getActivity(),rCode,Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

			}
		});
	}

	@Override
	public void onMyLocationChange(Location location) {
		if(location != null) {
			//如果想改变地图中心点
			getAddress(location.getLatitude(),location.getLongitude());
		}
	}

	public void getAddress(double lat,double lng){
		aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(lat, lng),16,0,0)));
		LatLonPoint latLonPoint = new LatLonPoint(lat,lng);
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
		geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
	}

	public void editor(){

	}


	/**
	 * 方法必须重写
	 */
	@Override
	public void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onPause() {
		super.onPause();
		mapView.onPause();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	public void onGetInputtips(List<Tip> list, int i) {
		if(list!=null) {
			mlist.clear();
			for(Tip tip:list){
				if(tip.getPoiID()!=null&&tip.getPoint()!=null){
					mlist.add(tip);
				}
			}
			adapter.notifyDataSetChanged();
		}
	}
}
